<template>
  <el-card class="article-detail-card" v-if="article">
    <h2>{{ article.title }}</h2>

    <el-descriptions :column="1" border label-class-name="label-style">
      <el-descriptions-item label="ID">{{ article.id }}</el-descriptions-item>
      <el-descriptions-item label="分类">{{
        categoriesMap[article.categoryId] || '未知分类'
      }}</el-descriptions-item>
      <el-descriptions-item label="创建时间">{{ article.createdAt }}</el-descriptions-item>
      <el-descriptions-item label="更新时间">{{ article.updatedAt }}</el-descriptions-item>
    </el-descriptions>

    <div v-if="isContentParsed" class="article-content">
      <quill-editor
        ref="quillEditorRef"
        :content="initialContent"
        readOnly
        theme="bubble"
        style="min-height: 500px; margin-top: 20px;"
      />
    </div>

    <div v-else class="raw-content">
      <el-alert title="无法解析富文本内容" type="warning" show-icon :closable="false" />
      <pre>{{ article.content }}</pre>
    </div>
  </el-card>

  <el-skeleton v-else-if="loading" :rows="6" animated />

  <el-alert v-else-if="error" :title="error" type="error" show-icon :closable="false" />
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue';
import { useRoute } from 'vue-router';
import { QuillEditor } from '@vueup/vue-quill';
import 'quill/dist/quill.bubble.css';
import { useCategories } from '../composables/useCategory'; // 引入 useCategories
import { useArticle } from '../composables/useArticle';

const route = useRoute();
const id = route.params.id;

// 使用组合函数
const { categoriesMap, fetchCategories } = useCategories();
const { article, loading, error, isContentParsed, initialContent, fetchArticle } = useArticle(id);
const quillEditorRef = ref(null);

let quillInstance = null;

onMounted(async () => {
  await fetchCategories(); // 调用组合函数获取分类
  await fetchArticle();
});

onBeforeUnmount(() => {
  if (quillInstance) {
    quillInstance.off('text-change');
    quillInstance = null;
  }
});
</script>

<style scoped>
.article-detail-card {
  max-width: 960px;
  margin: 2rem auto;
  padding: 2rem;
}

.label-style {
  font-weight: bold;
  width: 120px;
  text-align: center;
}

.article-content pre,
.raw-content pre {
  background-color: #f5f7fa;
  padding: 1rem;
  border-radius: 4px;
  white-space: pre-wrap;
  word-break: break-word;
  color: #333;
}

.el-alert {
  margin-top: 1rem;
}
</style>